# app.py
from dotenv import load_dotenv
load_dotenv()

from flask import Flask, render_template, request, redirect, url_for, flash
from config import Config
from models import db, Event
from send_email import mail, init_mail, send_notification
from flask_migrate import Migrate
import json

app = Flask(__name__)
app.config.from_object(Config)

# Initialize extensions
db.init_app(app)
migrate = Migrate(app, db)
init_mail(app)

@app.route('/')
def index():
    events = Event.query.order_by(Event.timestamp.desc()).limit(10).all()
    return render_template('index.html', events=events)

@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        try:
            # 验证 Webhook 签名（可选）
            # secret = app.config['WEBHOOK_SECRET']
            # Implement your signature verification here if needed

            data = request.json
            event_type = data.get('type', 'unknown')
            event_data = json.dumps(data)
            event = Event(event_type=event_type, data=event_data)
            db.session.add(event)
            db.session.commit()
            
            # 发送邮件通知
            send_notification(
                subject=app.config['EMAIL_SUBJECT'],
                recipients=[app.config['EMAIL_RECIPIENT']],
                template='email/new_event',
                event=event,
                email_body=app.config['EMAIL_BODY']
            )
            
            return '', 204
        except Exception as e:
            app.logger.error(f'Error processing webhook: {e}')
            return 'Internal Server Error', 500

@app.route('/events')
def view_events():
    page = request.args.get('page', 1, type=int)
    per_page = 20
    pagination = Event.query.order_by(Event.timestamp.desc()).paginate(
        page=page, per_page=per_page, error_out=False
    )
    events = pagination.items
    return render_template('view_events.html', events=events, pagination=pagination)

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

if __name__ == '__main__':
    app.run(debug=True)
